package com.gutsyzhan.bilibili.controller;

import com.alibaba.fastjson.JSONObject;
import com.gutsyzhan.bilibili.domain.JsonResponse;
import com.gutsyzhan.bilibili.domain.PageResult;
import com.gutsyzhan.bilibili.domain.User;
import com.gutsyzhan.bilibili.domain.UserInfo;
import com.gutsyzhan.bilibili.service.UserFollowingService;
import com.gutsyzhan.bilibili.service.UserService;
import com.gutsyzhan.bilibili.support.UserSupport;
import com.gutsyzhan.bilibili.util.RSAUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private UserSupport userSupport;

    @Resource
    private UserFollowingService userFollowingService;

    /**
     * 获取用户信息
     */
    @GetMapping("/users")
    public JsonResponse<User> getUserInfo(){
        Long userId = userSupport.getCurrentUserId();
        User user = userService.getUserInfo(userId);
        return new JsonResponse<>(user);
    }

    /**
     * 获取RSA公钥字符串
     */
    @GetMapping("/ras-pks")
    public JsonResponse<String> getRsaPublicKeyStr(){
        String publicKeyStr = RSAUtil.getPublicKeyStr();
        return JsonResponse.success(publicKeyStr);
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/users")
    public JsonResponse<String> addUser(@RequestBody User user){
        userService.addUser(user);
        return JsonResponse.success();
    }

    /**
     * 用户登录
     * @param user
     * @return
     */
    @PostMapping("/user-tokens")
    public JsonResponse<String> login(@RequestBody User user) throws Exception {
        String token = userService.login(user);
        return JsonResponse.success(token);
    }

    /**
     * 更新用户账号信息
     * @param user
     * @return
     */
    @PutMapping ("/users")
    public JsonResponse<String> updateUsers(@RequestBody User user) throws Exception {
        Long userId = userSupport.getCurrentUserId();
        user.setId(userId);
        userService.updateUsers(user);
        return JsonResponse.success();
    }

    /**
     * 更新用户基本信息
     * @param userInfo
     * @return
     */
    @PutMapping ("/user-infos")
    public JsonResponse<String> updateUserInfos(@RequestBody UserInfo userInfo) throws Exception {
        Long userId = userSupport.getCurrentUserId();
        userInfo.setUserId(userId);
        userService.updateUserInfos(userInfo);
        return JsonResponse.success();
    }

    /**
     * 通过昵称搜索用户基本信息并以列表形式返回
     * @param pageNo
     * @param pageSize
     * @param nick
     * @return
     */
    @GetMapping ("/user-infos")
    public JsonResponse<PageResult<UserInfo>> pageListUserInfos(@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                                                                @RequestParam(value = "pageSize", required = false, defaultValue = "10")Integer pageSize,
                                                                @RequestParam("nick")String nick){
        Long userId = userSupport.getCurrentUserId();
        JSONObject params = new JSONObject();
        params.put("pageNo", pageNo);
        params.put("pageSize", pageSize);
        params.put("nick", nick);
        params.put("userId", userId);
        //1、通过nick查询分页查询用户基本信息
        PageResult<UserInfo> userInfoPageResult = userService.pageListUserInfos(params);
        //2、将查询得到的信息与用户关注信息进行绑定
        if(userInfoPageResult.getTotal() > 0){
            List<UserInfo> checkUserInfoList = userFollowingService.checkFollowingStatus(userInfoPageResult.getList(), userId);
            userInfoPageResult.setList(checkUserInfoList);
        }
        return new JsonResponse<>(userInfoPageResult);
    }

    /**
     * 用户登录，返回双Token（AccessToken和RefreshToken）
     */
    @PostMapping("user-dts")
    public JsonResponse<Map<String, Object>> loginForDts(@RequestBody User user) throws Exception {
        Map<String, Object> map = userService.loginForDts(user);
        return new JsonResponse(map);
    }

    /**
     * 用户退出登录，使用双Token
     * @param request
     * @return
     */
    @DeleteMapping("/refresh-tokens")
    public JsonResponse<String> logout(HttpServletRequest request){
        String refreshToken = request.getHeader("refreshToken");
        Long userId = userSupport.getCurrentUserId();
        userService.logout(userId, refreshToken);
        return JsonResponse.success();
    }

    /**
     * 刷新用户AccessToken
     */
    @PostMapping("/access-tokens")
    public JsonResponse<String> refreshAccessToken(HttpServletRequest request) throws Exception {
        String refreshToken = request.getHeader("refreshToken");
        Long userId = userSupport.getCurrentUserId();
        String accessToken = userService.refreshAccessToken(userId, refreshToken);
        return JsonResponse.success(accessToken);
    }
}
